package com.hzf.wxplatform.web.controller.manager.auth;

import com.google.gson.Gson;
import com.hzf.api.rpc.api.ApiService;
import com.hzf.common.base.BaseController;
import com.hzf.common.face.*;
import com.hzf.common.face.faceModel.FaceEntity;
import com.hzf.common.util.*;
import com.hzf.ucenter.dao.model.*;
import com.hzf.wxplatform.common.WxplatformResult;
import com.hzf.wxplatform.common.WxplatformResultConstant;
import com.hzf.wxplatform.common.utils.UcenterUserUtils;
import com.hzf.wxplatform.web.utils.SMSUtils;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/authRole")
public class AuthRoleController extends BaseController {
    @Autowired
    ApiService apiService;
    @RequestMapping(value = "/auth")
    public String auth(Model model,int type, HttpServletRequest request, HttpServletResponse response) {

        HttpSession session = request.getSession();
        UcenterUser ucenterUser = new UcenterUser();
        byte[]user =  UcenterUserUtils.getUser(session);
        if(null==user){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(user);
        if(null==ucenterUser){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        UcenterAuthInfoExample example = new UcenterAuthInfoExample();
        example.createCriteria().andUserIdEqualTo(ucenterUser.getId());
        UcenterAuthInfo ucenterAuthInfo = apiService.selectUserinfo(example);
        if(null!=ucenterAuthInfo){
            String name="";
            if(ucenterAuthInfo.getAuthType()==6){
                name="材料商";
            }else if(ucenterAuthInfo.getAuthType()==3){
                name="设计师";
            }
            else if(ucenterAuthInfo.getAuthType()==4){
                name="工人";
            }
            model.addAttribute("data","您已认证"+name);

            return thymeleaf("/404");

        }
        model.addAttribute("type",type);
        return thymeleaf("/auth/Renzheng");

    }
    @RequestMapping(value = "/phoneCode", method = RequestMethod.POST)
    @ResponseBody
    public Object phoneCode(@RequestParam(value = "phone", required = false) String phone, Model model, HttpServletRequest request, HttpServletResponse response) {

        return getCheckCode("custom", phone);
    }

    @RequestMapping(value = "/checkCode", method = RequestMethod.POST)
    @ResponseBody
    public Object checkCode(@RequestParam(value = "phone", required = false) String phone, @RequestParam(value = "code", required = false) String code, Model model, HttpServletRequest request, HttpServletResponse response) {
        CheckCode chacheCode = (CheckCode) EhCacheUtil.get("hzf-wxplatform-web-ehcache", phone);
        if (chacheCode.getCode().equals(code)) {
            return new WxplatformResult(WxplatformResultConstant.SUCCESS, "发送成功");
        }
        return new WxplatformResult(WxplatformResultConstant.FAILED, "请确定手机号是否正确");
    }

    private Object getCheckCode(String userType, String mobile) {
        // 1. 发送验证码

        CheckCode checkCode = SMSUtils.sendCheckCode(mobile);

        // 2. 缓存验证码
        ResponseCode responseCode = ResponseCode.SYSTEM_ERROR;
        System.out.println(checkCode.getCode());
        EhCacheUtil.put("hzf-wxplatform-web-ehcache", mobile, checkCode);
        return new WxplatformResult(WxplatformResultConstant.SUCCESS, "绑定成功");

    }

    @RequestMapping(value = "/authSave", method = RequestMethod.POST)
    @ResponseBody
    public Object authSave(UcenterUserAuth ucenterUserAuth,int type,Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        UcenterUser ucenterUser = new UcenterUser();
        byte[]user =  UcenterUserUtils.getUser(session);
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(user); if(null==ucenterUser){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        ucenterUserAuth.setAuthType(type);
        ucenterUserAuth.setUserId(ucenterUser.getId());
        UcenterUserAuthExample ucenterUserAuthExample = new UcenterUserAuthExample();
        ucenterUserAuthExample.createCriteria().andUserIdEqualTo(ucenterUserAuth.getUserId()).andAuthTypeEqualTo(ucenterUserAuth.getAuthType());
        List<UcenterUserAuth> list = apiService.selectUcenterUserAuth(ucenterUserAuthExample);
        UcenterAuthBusiness ucenterAuthBusiness = ucenterUserAuth.getUcenterAuthBusiness();

        if (list.size() >= 2) {
            ucenterUserAuth = apiService.insertUcneterUserAuth(ucenterUserAuth, type);
            if (null == ucenterUserAuth) {
                return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
            }
            if(type==6){
                 ucenterAuthBusiness = ucenterUserAuth.getUcenterAuthBusiness();
                ucenterAuthBusiness.setAuthId(ucenterUserAuth.getId());
                ucenterAuthBusiness.setUserId(ucenterUser.getId());
                ucenterAuthBusiness = apiService.insertUcenterAuthBusiness(ucenterAuthBusiness);
                if (null == ucenterAuthBusiness) {
                    return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                }
            }

            UcenterAuthType ucenterAuthType = new UcenterAuthType();
            ucenterAuthType.setAuthId(ucenterUserAuth.getId());
            ucenterAuthType.setAuthStatus(0);
            ucenterAuthType.setAuthContent("调用接口二次未审核成功");
            apiService.insetUcenterAuthType(ucenterAuthType);


            return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已转人工审核");

        }
        FaceCard faceCard = new FaceCard();
        faceCard.setApi_key(PropertiesFileUtil.getInstance("hzf-face").get("face.apikey"));
        faceCard.setApi_secret(PropertiesFileUtil.getInstance("hzf-face").get("face.apiSecret"));
        faceCard.setImage_url(ucenterUserAuth.getCardFront());
        faceCard.setLegality(1);
        JSONObject jsonObject = FaceUtils.OCRIDCardAPI(faceCard);
        FaceReturn faceReturn = new Gson().fromJson(jsonObject.toString(), FaceReturn.class);
        if (faceReturn.getCards().size() != 0) {
            Cards cards1 = new Cards();
            for (Cards cards : faceReturn.getCards()) {
                if (null != cards.getLegality()) {
                    cards1.setLegality(cards.getLegality());
                }
                if (null != cards.getAddress()) {
                    cards1.setAddress(cards.getAddress());
                }
                if (null != cards.getBirthday()) {
                    cards1.setBirthday(cards.getBirthday());
                }
                if (null != cards.getId_card_number()) {
                    cards1.setId_card_number(cards.getId_card_number());
                }
                if (null != cards.getName()) {
                    cards1.setName(cards.getName());
                }
                if (null != cards.getGender()) {
                    cards1.setGender(cards.getGender());
                }

            }


            if (cards1.getLegality().getIDPhoto() > cards1.getLegality().getEdited() && cards1.getLegality().getIDPhoto() > cards1.getLegality().getPhotocopy() && cards1.getLegality().getIDPhoto() > cards1.getLegality().getScreen() && cards1.getLegality().getIDPhoto() > cards1.getLegality().getTemporaryIDPhoto()) {
                FaceModel faceModel = new FaceModel();
                faceModel.setImage_url1(ucenterUserAuth.getCardFront());
                faceModel.setImage_url2(ucenterUserAuth.getFrontDocument());
                faceModel.setApi_secret(PropertiesFileUtil.getInstance("hzf-face").get("face.apiSecret"));
                faceModel.setApi_key(PropertiesFileUtil.getInstance("hzf-face").get("face.apikey"));
                FaceEntity faceEntity = FaceUtils.httpPost(faceModel);
                if (faceEntity.getConfidence() != 0) {
                    if (faceEntity.getConfidence() > faceEntity.getThresholds().getLe5()) {
                        ucenterUserAuth = apiService.insertUcneterUserAuth(ucenterUserAuth, type);
                        if (null == ucenterUserAuth) {
                            return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                        }
                        if(type==6){
                            ucenterAuthBusiness.setAuthId(ucenterUserAuth.getId());
                            ucenterAuthBusiness.setUserId(ucenterUser.getId());
                            ucenterAuthBusiness = apiService.insertUcenterAuthBusiness(ucenterAuthBusiness);
                            if (null == ucenterAuthBusiness) {
                                return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                            }
                        }
                        UcenterAuthType ucenterAuthType = new UcenterAuthType();
                        ucenterAuthType.setAuthId(ucenterUserAuth.getId());
                        ucenterAuthType.setAuthStatus(1);
                        ucenterAuthType.setAuthContent("调用接口一次审核成功");
                        apiService.insetUcenterAuthType(ucenterAuthType);

                        UcenterAuthInfo ucenterAuthInfo = new UcenterAuthInfo();
                        ucenterAuthInfo.setAuthType(type);
                        ucenterAuthInfo.setCardAddress(cards1.getAddress());
                        ucenterAuthInfo.setCardFront(ucenterUserAuth.getCardFront());
                        ucenterAuthInfo.setFrontDocument(ucenterUserAuth.getFrontDocument());
                        ucenterAuthInfo.setIdCard(cards1.getId_card_number());
                        ucenterAuthInfo.setName(cards1.getName());
                        if(type==6){
                            ucenterAuthInfo.setOfficeDocument(ucenterAuthBusiness.getOfficeDocument());
                            ucenterAuthInfo.setOfficeLicense(ucenterAuthBusiness.getOfficeLicense());
                        }

                        ucenterAuthInfo.setPhone(ucenterUserAuth.getPhone());
                        ucenterAuthInfo.setUserId(ucenterUser.getId());
                        ucenterUser.setPhone(ucenterAuthInfo.getPhone());
                        ucenterUser.setUserName(ucenterAuthInfo.getName());
                        ucenterUser.setSex(cards1.getGender());
                        ucenterUser.setAuthInfoId(ucenterUserAuth.getId());
                        ucenterUser.setAuthInfo(type);
                        int a =apiService.update(ucenterUser);
                        String key = "user"+ucenterUser.getId().toString();
                        RedisUtil.del_save(key.getBytes(), ByteUtils.ObjectToByte(ucenterUser));
                        System.out.println(ucenterUser.getAuthInfoId());
                        System.out.println("执行了");
                        ucenterAuthInfo = apiService.insetUcenterAuthInfo(ucenterAuthInfo);
                        if (null == ucenterAuthInfo) {
                            return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                        }


                        return new WxplatformResult(WxplatformResultConstant.SUCCESS, "申请成功");
                    } else {
                        ucenterUserAuth = apiService.insertUcneterUserAuth(ucenterUserAuth, type);
                        if (null == ucenterUserAuth) {
                            return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                        }
                        if(type==6){
                            ucenterAuthBusiness.setAuthId(ucenterUserAuth.getId());
                            ucenterAuthBusiness.setUserId(ucenterUser.getId());
                            ucenterAuthBusiness = apiService.insertUcenterAuthBusiness(ucenterAuthBusiness);
                            if (null == ucenterAuthBusiness) {
                                return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                            }
                        }
                        UcenterAuthType ucenterAuthType = new UcenterAuthType();
                        ucenterAuthType.setAuthId(ucenterUserAuth.getId());
                        ucenterAuthType.setAuthStatus(2);
                        ucenterAuthType.setAuthContent("调用接口二次未审核成功");
                        apiService.insetUcenterAuthType(ucenterAuthType);

                        return new WxplatformResult(WxplatformResultConstant.FAILED, "身份证和自拍不匹配");
                    }
                } else {
                    ucenterUserAuth = apiService.insertUcneterUserAuth(ucenterUserAuth, type);
                    if (null == ucenterUserAuth) {
                        return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                    }
                    if(type==6){
                        ucenterAuthBusiness.setAuthId(ucenterUserAuth.getId());
                        ucenterAuthBusiness.setUserId(ucenterUser.getId());
                        ucenterAuthBusiness = apiService.insertUcenterAuthBusiness(ucenterAuthBusiness);
                        if (null == ucenterAuthBusiness) {
                            return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                        }
                    }
                    UcenterAuthType ucenterAuthType = new UcenterAuthType();
                    ucenterAuthType.setAuthId(ucenterUserAuth.getId());
                    ucenterAuthType.setAuthStatus(2);
                    ucenterAuthType.setAuthContent("调用接口二次未审核成功");
                    apiService.insetUcenterAuthType(ucenterAuthType);

                    return new WxplatformResult(WxplatformResultConstant.FAILED, "身份证和自拍不匹配");

                }
            } else {
                ucenterUserAuth = apiService.insertUcneterUserAuth(ucenterUserAuth, type);
                if (null == ucenterUserAuth) {
                    return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                }
                if(type==6){
                    ucenterAuthBusiness.setAuthId(ucenterUserAuth.getId());
                    ucenterAuthBusiness.setUserId(ucenterUser.getId());
                    ucenterAuthBusiness = apiService.insertUcenterAuthBusiness(ucenterAuthBusiness);
                    if (null == ucenterAuthBusiness) {
                        return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                    }
                }

                UcenterAuthType ucenterAuthType = new UcenterAuthType();
                ucenterAuthType.setAuthId(ucenterUserAuth.getId());
                ucenterAuthType.setAuthStatus(2);
                ucenterAuthType.setAuthContent("调用接口二次未审核成功");
                apiService.insetUcenterAuthType(ucenterAuthType);

                return new WxplatformResult(WxplatformResultConstant.FAILED, "身份证件非身份证原件");
            }
        }
        else {
            ucenterUserAuth = apiService.insertUcneterUserAuth(ucenterUserAuth, type);
            if (null == ucenterUserAuth) {
                return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
            }
            if(type==6){
                ucenterAuthBusiness.setAuthId(ucenterUserAuth.getId());
                ucenterAuthBusiness.setUserId(ucenterUser.getId());
                ucenterAuthBusiness = apiService.insertUcenterAuthBusiness(ucenterAuthBusiness);
                if (null == ucenterAuthBusiness) {
                    return new WxplatformResult(WxplatformResultConstant.SUCCESS, "已有绑定信息，不需要重新绑定。如有疑问请联系客服");
                }
            }
            UcenterAuthType ucenterAuthType = new UcenterAuthType();
            ucenterAuthType.setAuthId(ucenterUserAuth.getId());
            ucenterAuthType.setAuthStatus(2);
            ucenterAuthType.setAuthContent("调用接口二次未审核成功");
            apiService.insetUcenterAuthType(ucenterAuthType);

        }
        return new WxplatformResult(WxplatformResultConstant.FAILED, "身份证信息错误");

    }
}
